﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using PortableVersion.Core.FileSystem.Services;

namespace PortableVersion.Core.General
{
    public static class SerializationHelper
    {
        public static T Load<T>(string path)
        {
            path.AssertNotNull("path");
            if (!File.Exists(path))
            {
                throw new ArgumentException(String.Format("'{0}' does not exist.", path), "path");
            }
            var file = default(StreamReader);
            try
            {
                file = File.OpenText(path);
                var serializer = new XmlSerializer(typeof (T));
                return (T)serializer.Deserialize(file);
            }
            finally
            {
                if (file != null) file.Close();
            }
        }

        public static void Save<T>(T data, string path)
        {
            var serializer = new XmlSerializer(typeof (T));
            var writer = new StreamWriter(path);
            try
            {
                serializer.Serialize(writer, data);
            }
            finally
            {
                writer.Close();
            }
        }
    }
}
